<template>
	<view id="body">
		<view class="form">	
			<uni-section class="mb-10" title="1.选择发布类型" type="line" titleColor="#909399" ></uni-section>
			<view class="type-input">
				<u--input
				    placeholder="请选择发布类型"
				    border="surround" 
				    v-model="issueType"
				    @tap="typeShowOpen"
					readonly=true
				></u--input>
			</view>
			<u-picker :show="typeShow" ref="uPicker" :columns="columns" @cancel="typeShowClose" @confirm="typeConfirm" @change="changeHandler"></u-picker> 
			<!-- 内容 -->
			<uni-section class="mb-10" title="2.发布内容" type="line" titleColor="#909399"></uni-section>
			<view class="content-input">
				<u--textarea v-model="content" placeholder="请输入发布内容"  count="true"  maxlength=400></u--textarea>
			</view>
			<!-- 时间选择 -->
			<uni-section class="mb-10" title="3.取件时间" type="line" titleColor="#909399"></uni-section>
			<view class="time-input">
				<uni-datetime-picker
				placeholder="立即取件"
				hide-second=true
				:start="getNowTime"
				:end="getNowTime+1296000000"
				@change="timeConfirm"
				 />
			</view>
			<!--图片信息-->
			<uni-section class="mb-10" title="4.图片信息(选填)" type="line" titleColor="#909399"></uni-section>
			<view class="img-input">
				<image :src="item" v-if="item" mode="" class="imglist" v-for="(item,index) in imagesList" :key="item" @tap="ViewImage(index)" @longpress="deleteImg(index)"></image>
				<view class="box">
					<text class="t-icon t-icon-Rrl_s_114" style="width: 80rpx; height: 80rpx;margin-top: 36rpx;" @click="addImages()"></text>
				</view>
			</view>
			<!-- 备注信息 -->
			<uni-section class="mb-10" title="5.备注信息(选填)" type="line" titleColor="#909399"></uni-section>
			<view class="beizhu-input">
				<u--textarea v-model="bezhu" placeholder="请输入备注内容"  count="true"  maxlength=100 ></u--textarea>
			</view>
			<!-- 是否就近购买 -->
			<uni-section class="mb-10" title="购买地址" type="line" titleColor="#909399"></uni-section>
			<view class="buyaddress-input">
				<radio-group @change="radioChange">
					<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in checkAddressItems" :key="item.value">
						<view>
							<radio :value="item.value" :checked="index === checkAddressCurrent" />
						</view>
						<view>{{item.name}}</view>
					</label>
				</radio-group>
			</view>
			<!-- 地址 -->
			<uni-section class="mb-10" title="6.地址信息" type="line" titleColor="#909399"></uni-section>
			<view class="address-input">
				<u--input placeholder="请输入地址" v-model="address"  clearable></u--input>
			</view>
			<view class="addressbutton"> 
				<u-button
					text="选择地址"
					size="normal"
					type="primary"
					@click="addressclick"
				></u-button>
			</view>
			<!-- 金额 -->
			<uni-section class="mb-10" title="7.发布金额" type="line" titleColor="#909399"></uni-section>
			<view class="price-input">
				<u--input 
				placeholder="请输入价格"  
				@input="checknumber()"
				type = number
				v-model="price"  
				clearable></u--input> 
			</view>
			<text style="margin-left: 20rpx;color: #3c9cff;">元</text>
			<!-- 是否开启匿名 -->
			<text style="margin-left: 84rpx; font-size: 28rpx; color: #909399;">匿名</text>
			<view class="anonymous">  
				<u-switch v-model="huadong" activeColor=" #3c9cff" ></u-switch>
			</view>
			<!-- 发布按钮 -->
			<view class="fabubutton">
				<u-button
					text="创             建"
					size="normal"
					type="primary"
					@click="fbclick"
				></u-button>
			</view>
		</view> 
	</view> 
</template>  

<script> 
	// import OSS from 'ali-oss' 
	// import {uploadImgToOss,deleteImg} from "../../static/service/aliyoss/config.js"
	// import {uploadImage} from '../../js_sdk/yushijie-ossutil/ossutil/uploadFile.js'
	// import {http} from "../../static/service/requestAddress/rtas.js"
	const http = 'https://www.uinav.com'
	export default {
		data() {
			return{ 
				typeShow: false,
				issueType:"", //类型
				order_index:[],//订单类型下标数组，用于发布封装订单
				content:"",//内容
				getNowTime: Number(new Date()), //当前时间
				getGoodsTime: '', //取件时间
				bezhu:"",//备注
				price:"",//价格
				order_img:"",//订单图片
				huadong:false,//匿名滑动选择器
				contacts:"",//联系人
				contacts_phone:"",//联系人电话
				checkAddressItems: [{
						value: '就近购买',
						name: '就近购买',
						checked: 'true'
					},
					{
						value: '指定地址',
						name: '指定地址'
					},
				],
				checkAddressCurrent: 0,
				addressType:"",
				address:"",//地址
				addressInfo:{ //地址信息对象
					id:"",
					name:"",
					phone:"",
					address:"",
					defaultaddress:false,
				},
                columns: [
                    ['帮我做', '帮我买',"帮我送","其他需求"],
					["寄取物品","打印资料","食堂打饭","排队服务","代写服务","其他"]
				],
                columnData: [
				["寄取物品","打印资料","食堂打饭","排队服务","代写服务","其他"],
                ["烟酒","零食","药品","小吃","水果","饮料奶茶","主食套餐","生活用品","学习用品","其他"],
				['文件', '钥匙', '花', '蛋糕',"其他"],
				["租借","拼车",],
                ],
				imagesList:[],//图片数组
				receiveImgList: "",//上传图片返回的链接
			}
		},
		onLoad() {
				//清空数据
				this.issueType = "", //类型
				this.order_index=[],//订单类型下标数组，用于发布封装订单
				this.content="",//内容
				this.getGoodsTime = "", //取件时间
				this.checkAddressCurrent= 0, //就近购买的默认值
				this.addressType="", //是否就近购买
				this.bezhu="",//备注
				this.price="",//价格
				this.order_img="",//订单图片
				this.huadong=false,//匿名滑动选择器
				this.contacts="",//联系人
				this.contacts_phone="",//联系人电话
				this.address="",//地址
				this.checkAddressItems= [{
						value: '就近购买',
						name: '就近购买',
						checked: 'true'
					},
					{
						value: '指定地址',
						name: '指定地址'
					},
				],
				this.addressInfo ={ //地址信息对象
					id:"",
					name:"",
					phone:"",
					address:"",
					defaultaddress:false,
				},
				this.imagesList = []//图片数组
		},
		onShow() {
			//设置tabbar
			var str = uni.getStorageSync("tabbar")
			if(typeof str == 'string' && str.length != 0){
				var num = parseInt(str)
				if(num > 0){
					uni.setTabBarBadge({ //显示数字
						index: 1, //tabbar下标
						text:""+num,//数字
						success() {
						console.log("设置成功") 
						},
						fail(e){
						   console.log("设置失败"+JSON.stringify(e))
						}
					})
					uni.setStorageSync("tabbar",JSON.stringify(num))
					this.$forceUpdate()
				}
			}
			//监听地址页面传递的参数
			uni.$on("address",res=>{
				this.$nextTick(()=>{ //延伸步骤做伪刷新 
				    this.address = res.address
					this.contacts = res.name
					this.contacts_phone = res.phone
				})
			})
			
		},
		onUnload() {
				//清空数据
				this.issueType = "", //类型
				this.order_index=[],//订单类型下标数组，用于发布封装订单
				this.content="",//内容
				this.getGoodsTime = "", //取件时间
				this.checkAddressCurrent= 0,
				this.addressType="",
				this.bezhu="",//备注
				this.price="",//价格
				this.order_img="",//订单图片
				this.huadong=false,//匿名滑动选择器
				this.contacts="",//联系人
				this.contacts_phone="",//联系人电话
				this.address="",//地址
				this.checkAddressItems= [{
						value: '就近购买',
						name: '就近购买',
						checked: 'true'
					},
					{
						value: '指定地址',
						name: '指定地址'
					},
				],
				this.addressInfo ={ //地址信息对象
					id:"",
					name:"",
					phone:"",
					address:"",
					defaultaddress:false,
				},
				this.imagesList = []//图片数组
		},
		methods: {
			typeShowOpen(){ //点击选择发布类型输入框
				this.typeShow = true
			},
			typeShowClose(){//关闭选择框
				this.typeShow=false
			},
			changeHandler(e) {
                const {
                    columnIndex, //
                    value,  //选择的结果
                    values, // values为当前变化列的数组内容
                    index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
                    picker = this.$refs.uPicker
                } = e
                // 当第一列值发生变化时，变化第二列(后一列)对应的选项
                if (columnIndex === 0) {
                    // picker为选择器this实例，变化第二列对应的选项
                    picker.setColumnValues(1, this.columnData[index])
                }
            },
			// 回调参数为包含columnIndex、value、values
			typeConfirm(e) {
				console.log(JSON.stringify(e))
				this.order_index = e.indexs
				this.issueType = e.value[0]+"  /  "+e.value[1]
                this.typeShow = false
			},
			// value:返回所选时间戳，mode:当前模式
			timeConfirm(e) {
				console.log(JSON.stringify(e))
				this.getGoodsTime = e.value
			},
			// 上传图片
			addImages() {
				uni.$emit("uploadimg",false)
				var urlt 
				var that = this
				var promise = new Promise(function(resolve,reject){
				if(that.imagesList.length < 8){
					uni.chooseImage({
						count: 3, // 默认最多一次选择8张图
						sourceType: ['album', 'camera'], //图片来源
						success: res => {
							console.log("图片路径是："+ res.tempFilePaths);
							// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
							var tempFilePaths = res.tempFilePaths;
							//支持多图上传
							var falge = false//是否有不合法数据格式标记
							for (var i = 0; i < res.tempFilePaths.length; i++) {
								//对上传的图片校验
								var str = tempFilePaths[i].slice(tempFilePaths[i].length - 3,tempFilePaths[i].length)
								var strhz = ["jpg","png","gif"]
								var T = strhz.indexOf(str)
								if(T == -1){
									falge = true
									continue
								}
								if(that.imagesList.length < 3){
									//显示消息提示框
									uni.showLoading({
										mask: true
									})
									that.imagesList.push(tempFilePaths[i])
								}else{
									uni.$u.toast("图片只能上传3张！")
									break
								}
							}
							uni.hideLoading();
							if(falge){
								uni.$u.toast("上传成功，以过滤格式不正确图片！")
							}else{
								uni.$u.toast("图片上传成功！")
							}
							resolve()
						}
					})
				}else{
					uni.$u.toast("图片只能上传3张！")
				}
				})
				promise.then(res=>{
					setTimeout(function(){
						uni.$emit("uploadimg",true)
					},500)
				})
			},
			//单选框切换
			radioChange: function(evt) {
				for (let i = 0; i < this.checkAddressItems.length; i++) {
					if (this.checkAddressItems[i].value === evt.detail.value) {
						this.checkAddressCurrent = i;
						this.addressType = evt.detail.value;
						break;
					}
				}
			},
			
			//预览图片
			ViewImage(index) {
				uni.previewImage({
					urls: this.imagesList,
					current: index
				});
			},
			//地址信息按钮跳转
			addressclick(){
				uni.navigateTo({
					// url:"/pages/massage/orderDetails",
					 url:'/address/address'
				})
			},
			//价格输入框检查只能为数字
			checknumber(){
				 let num = /^[1-9]([0-9])*$/
				 var b = num.test(this.price)
				 if(! b){
					setTimeout(() => { 
						this.price = ""  
						uni.$u.toast("价格只能是数字并且不能为0")
					},10)
				}
			},
			//图片长按删除
			deleteImg(index){
				var list = []
				for(var i = 0;i<this.imagesList.length;i++){
					if(index == i){
						continue
					}else{
						list.push(this.imagesList[i])
					}
				}
				this.imagesList = list
			},
			async fbclick(){
				uni.showLoading({
				title: '正在创建订单中'
				})
				//1.发布信息检查
				var user = uni.getStorageSync('user')
				if(! user){
					uni.$u.toast("您还未登录，登录才能发布订单")
					return
				}else if(this.issueType == "" || this.issueType.length == 0){
					uni.$u.toast("类型不能为空")
					return
				// }else if (this.title == "" || this.issueType.length == 0 || this.title.length > 10){
				// 	uni.$u.toast("标题不能为空，并且长度小于10")
				// 	return
				}else if(this.content == "" || this.content.length == 0){
					uni.$u.toast("内容不能为空")
					return
				}else{
					//上传图片
					//显示消息提示框
					uni.showLoading({
						title:"正在创建中",
						mask: true
					})
					var path = this.issueType.replace(/\s*/g,"")
					// this.receiveImgList = await uploadImgToOss(this.imagesList,path)
					//请求参数数组
					var sendpost = [
						http+"buyorder",
						http+"sendorder",
						http+"workorder",
						http+"need",
					]
					//封装请求对象
					var hidename = 0//匿名
					if(this.huadong == true){
						hidename = 1
					}
					var postData = {
						id:"",//订单id
						type:this.order_index[1] + 1,//订单类型
						// title:this.title,//订单标题
						content:this.content,//订单内容
						orderImg:this.receiveImgList,//订单图片
						state:0,//订单状态
						remarks:this.bezhu,//订单备注
						price:this.price,//订单价格
						hideName:hidename,//是否匿名
						issueUser:(JSON.parse(user)).id,//发布用户
						issueUserName:(JSON.parse(user)).name,//发布用户名
						issueUserImg:(JSON.parse(user)).img,//发布用户头像
						contacts:this.contacts,//联系人姓名
						contactsPhone:this.contacts_phone,//联系人电话
						contactsAddress:this.address,//地址信息
						ordertypeid: this.order_index[0] + 1,//订单所属类型
					}	
					var URL = sendpost[this.order_index[0]]
					console.log('想后端发送请求'+URL)
					 uni.request({
						url:URL,
						method:"POST",
						data:postData,
						complete:(res) =>{
							if(res.data.code == 20011){
								uni.hideLoading()
								uni.$u.toast("订单创建成功！")
								uni.redirectTo({
								url:"/pages/massage/orderDetails?data="+ JSON.stringify(res.data.date)
								})
								uni.hideLoading()
							}else{
								uni.hideLoading()
								uni.$u.toast("订单创建失败，请重试！")
							}
						}
					})
				}
			},
		}
	} 
</script>

<style scoped>
	.type-input, .time-input, .title-input, .content-input, .beizhu-input, .buyaddress-input {
		width: calc(100vw - 40rpx);
		margin: 0 auto;
	}
	/deep/ .time-input .icon-calendar {
		padding: 0 5px !important;
	}
	.img-input{
		 max-height: 600rpx;
		 width: calc(100vw - 40rpx);
		 margin: 0 auto;
		 border-radius: 4px;
		 border-width: 0.5px !important;
		 border-color: #dadbde !important;
		 border-style: solid;
	 }
	 .imglist{
		 float: left;
		 width: 160rpx;
		 height: 160rpx;
		 margin: 8rpx 8rpx;
		 box-shadow: 0 0 1px #aaaaaa;
	 }
	 .box{
		 display: inline-block;
		 width: 160rpx;
		 height: 160rpx;
		 margin: 8rpx 8rpx;
		 box-shadow: 0 0 1px #aaaaaa;
		 text-align: center;
	 }
	 /* 地址信息 */
	.address-input{
		 display: inline-block;
		 margin-left: 20rpx;
		 width: 490rpx;
	}
	.addressbutton{ 
		display: inline-block;
		margin-left: 20rpx;
		width: 200rpx;
		height: 76rpx;
		float: right;
		margin-right: 20rpx;
	}
	/deep/ .u-button.data-v-5837df23 {
	    height: 38px;
	    position: relative;
	    align-items: center;
	    justify-content: center;
	    display: flex;
	    flex-direction: row;
	    box-sizing: border-box;
	    flex-direction: row;
	}
	/* 发布金额 */
	.price-input{
		width: 400rpx;
		margin-left: 20rpx;
		display: inline-block;
	}
	.anonymous{
		display: inline-block;
		float: right;
		margin-top: 12rpx;
		margin-right: 20rpx;
	}
	.fabubutton{
		width: calc(100vw - 40rpx);
		margin: 0 auto;
		margin-top: 60rpx;
		padding-bottom: 60rpx;
	}
	
	/* @import url("@/static/css/issue.css"); */
	page {
		background-color: #f5f5f5;
	}
</style>